package com.hmdp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        Set<ShopType> shopTypeSet;
        // 1.Redis查询店铺类型
        String shopTypeKey = RedisConstants.CACHE_SHOP_TYPE_KEY;
        Set<String> shopTypeJson = stringRedisTemplate.opsForSet().members(shopTypeKey);
        if (Objects.nonNull(shopTypeJson) && !shopTypeJson.isEmpty()){
            shopTypeSet = shopTypeJson.stream()
                    .map(st -> JSONUtil.toBean(st, ShopType.class))
                    .collect(Collectors.toSet());
            return Result.ok(shopTypeSet);
        }
        // 2.缓存未命中，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        shopTypeSet = new HashSet<>(shopTypes);
        if (ObjectUtil.isEmpty(shopTypeSet) || shopTypeSet.isEmpty()){
            return Result.fail("店铺类型无数据");
        }
        // 3.店铺类型数据写入缓存
        for (ShopType shopType : shopTypeSet) {
            stringRedisTemplate.opsForSet().add(shopTypeKey, JSONUtil.toJsonStr(shopType));
        }
        // 4.返回店铺类型数据
        return Result.ok(shopTypeSet);
    }
}
